package com.opencee.cloud.uaa.provider.service;

import cn.hutool.core.lang.Validator;
import com.opencee.cloud.base.api.IBaseAccountCredentialApi;
import com.opencee.cloud.base.api.IBaseUserApi;
import com.opencee.cloud.base.constants.BaseAccountType;
import com.opencee.cloud.base.entity.BaseAccountCredentialEntity;
import com.opencee.cloud.base.entity.BaseUserEntity;
import com.opencee.common.security.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author yadu
 */
@Service
public class UsernameUserDetailService implements UserDetailsService {
    @Autowired
    private IBaseAccountCredentialApi accountCredentialClient;
    @Autowired
    private IBaseUserApi userClient;

    /**
     * 账号密码登录认证信息获取
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BaseAccountCredentialEntity account = null;
        if (Validator.isEmail(username)) {
            account = accountCredentialClient.getBy(username, BaseAccountType.EMAIL.name()).getData();
        } else if (Validator.isMobile(username)) {
            account = accountCredentialClient.getBy(username, BaseAccountType.MOBILE.name()).getData();
        } else {
            account = accountCredentialClient.getBy(username, BaseAccountType.USERNAME.name()).getData();
        }
        if (account == null) {
            throw new UsernameNotFoundException("账户名与密码不匹配");
        }
        BaseUserEntity baseUserEntity = userClient.getById(account.getUserId()).getData();
        SecurityUser user = new SecurityUser();
        user.setUserId(baseUserEntity.getUserId());
        user.setUsername(baseUserEntity.getUserName());
        user.setPassword(account.getCredentials());
        user.setCredentialsNonExpired(true);
        user.setAccountNonLocked(baseUserEntity.getStatus() != 2);
        user.setAccountEnabled(baseUserEntity.getStatus() == 1);
        return user;
    }
}
